package site.shihuan.helpdesk.ticket.manager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import site.shihuan.helpdesk.common.util.IdWorker;
import site.shihuan.helpdesk.security.context.UserContext;
import site.shihuan.helpdesk.ticket.dao.TktLogTicketDao;
import site.shihuan.helpdesk.ticket.dao.TktReplyDao;
import site.shihuan.helpdesk.ticket.dao.TktTicketDao;
import site.shihuan.helpdesk.ticket.model.po.TktLogTicketPO;
import site.shihuan.helpdesk.ticket.model.po.TktReplyPO;
import site.shihuan.helpdesk.ticket.model.po.TktTicketPO;
import site.shihuan.helpdesk.ticket.model.ticket.TicketLogType;
import site.shihuan.helpdesk.ticket.model.vo.TicketReplyVO;

import java.util.List;

/**
 * 工单反馈
 *
 * @author 周世焕
 * @Date 2021/4/7 21:25
 */
@Service
public class TicketReplyManager {

    @Autowired
    private TktReplyDao replyDao;

    @Autowired
    private TktLogTicketDao logTicketDao;

    @Autowired
    private TktTicketDao ticketDao;

    /**
     * 根据ticketId查询回复列表
     * @param ticketId
     * @return
     */
    public List<TicketReplyVO> findReplyList(String ticketId) {
        return replyDao.selectByTicketId(ticketId);
    }

    /**
     * 保存最终方案
     * @param tenantId
     * @param ticketId
     * @param finalReply
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveFinalReply(String tenantId, String ticketId, String finalReply) {
        ticketDao.updateFinalReply(tenantId,ticketId,finalReply);
        TktLogTicketPO logTicketPO = new TktLogTicketPO();
        logTicketPO.setLogId(IdWorker.nextId());
        logTicketPO.setLogType(TicketLogType.SOLVED);
        logTicketPO.setTicketId(ticketId);
        logTicketPO.setLogData(finalReply);
        logTicketPO.setUserId(UserContext.getUserId());
        logTicketDao.insertSelective(logTicketPO);
    }
    /**
     * 保存工单回复
     * @param replyPO
     */
    public TktReplyPO saveReply(TktReplyPO replyPO) {
        if(replyPO.getReplyId() != null) {
            replyDao.updateByPrimaryKeySelective(replyPO);
            return replyPO;
        }
        replyPO.setReplyId(IdWorker.nextId());
        replyPO.setCreated(System.currentTimeMillis());
        replyDao.insertSelective(replyPO);
        TktLogTicketPO logTicketPO = new TktLogTicketPO();
        logTicketPO.setLogId(IdWorker.nextId());
        logTicketPO.setLogType(TicketLogType.COMMENT);
        logTicketPO.setTicketId(replyPO.getTicketId());
        logTicketPO.setLogData(replyPO.getContent());
        logTicketPO.setUserId(UserContext.getUserId());
        logTicketDao.insertSelective(logTicketPO);
        return replyPO;
    }

    /**
     * 删除回复
     * @param replyId
     * @param tenantId
     */
    public void deleteReply(String tenantId,String replyId) {
        replyDao.deleteByReplyIdAndTenantId(tenantId,replyId);
    }
}
